﻿using Casamiel.Domain.Entity;
using System;
using System.Collections.Generic;
using System.Text;

using Smooth.IoC.UnitOfWork.Interfaces;
using Casamiel.Domain;
using System.Threading.Tasks;
using Dapper;
using System.Linq;

namespace Casamiel.Infrastructure.Repositories
{
    /// <summary>
    /// Order discount coupon repository.
    /// </summary>
    public sealed class OrderDiscountCouponRepository : BaseRepository<Order_DiscountCouponEntity, int>, IOrderDiscountCouponRepository
    {
        public OrderDiscountCouponRepository(IDbFactory factory) : base(factory)
        {
        }

        /// <summary>
        /// Updates the status.
        /// </summary>
        /// <returns>The status.</returns>
        /// <param name="OrderBaseId">Order base identifier.</param>
        /// <param name="Status">Status.</param>
        /// <param name="uow">Uow.</param>
        public async Task<bool> UpdateStatus(int OrderBaseId, int Status, IUnitOfWork uow)
        {
			if (uow is null) {
				throw new ArgumentNullException(nameof(uow));
			}

			var sql = $"update  {Sql.Table<Order_DiscountCouponEntity>(uow.SqlDialect)} set Status=@Status where OrderBaseId=@OrderBaseId";
            return await uow.Connection.ExecuteAsync(sql.CheckSafeSql(), new { Status, OrderBaseId }, uow.Transaction).ConfigureAwait(true) > 0;
        }

        public async Task<List<Order_DiscountCouponEntity>> GetListByOrderBaseIdAsync<TSession>(int OrderBaseId) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                var sql = $"select top 1 * from  {Sql.Table<Order_DiscountCouponEntity>(session.SqlDialect)} where OrderBaseId=@OrderBaseId";
                var list= await session.QueryAsync<Order_DiscountCouponEntity>(sql, new { OrderBaseId }).ConfigureAwait(false);
                return list.ToList();
            }
        }

        public async Task<Order_DiscountCouponEntity> GetByOrderBaseIdAsync<TSession>(int OrderBaseId) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                var sql = $"select top 1 * from  {Sql.Table<Order_DiscountCouponEntity>(session.SqlDialect)} where OrderBaseId=@OrderBaseId";
                return await session.QuerySingleOrDefaultAsync<Order_DiscountCouponEntity>(sql, new { OrderBaseId }).ConfigureAwait(false);
            }
        }
    }
}
